<template>
	<div class="uploadlist">
		<draggable v-if="imgarray.length>0" :list="imgarray" :animation="100" :forceFallback="true"  @end="onEnd" @change="onMoveCallback" class="imgmove">
		     <transition-group>
		       <div v-for="(item, index) in imgarray" :key="item.page" class="boxsetdelecte" v-if="imgarray.length > 0">
					<b>{{index+1}}</b>
		         <img :src="$imgUrl1+item.url" alt="" style="width:200px;border: 1px solid #295cff80;">
				 <span><img src="../../assets/image/drag.png" alt="" style="width:24px;height:24px;"></span>
				 <div class="buttonboxedit">
					 <i @click="showViewer(index)">查看</i>
					 <i @click="deleteImage(index,item.url,item.itecaseflageid,item.page)">删除</i>
				 </div>
		       </div>
		     </transition-group>
		   </draggable>
		   <div class="upload-image">
		   		<input type="file" class="fileIndex" @change="handleFileChange" multiple accept="image/*" />
		   		<div class="uploadBoxinfo">
		   			点击上传<i>/</i>扫描图像
		   		</div>
		   </div>
		   <!-- 图片预览组件 -->
    <!-- <viewer :images="imgarray.map(img => img.url)" ref="viewer">
      <template #default>
        <img 
          v-for="(img, index) in imgarray" 
          :key="index" 
          :src="img.url" 
          style="display: none;"
        >
      </template>
    </viewer> -->
	</div>
</template>

<script>
// import { get, post, del, put } from '../../api/modelapi.js'
import draggable from 'vuedraggable';
import {uploadcardImage,deletecardImage,getitemcaseflagImage} from '../../api/api.js'
// import Viewer from 'v-viewer';
// import 'viewerjs/dist/viewer.css';
export default {
  name: 'UploadImage',
  props: {
	modudellist:{
		type: Array,
		default: () => []
	},
	examNoLength:{
		type: Number,
		default: () => ''
	},
	answerCardPages:{
		type: Number,
		default: () => ''
	}
  },
  data() {
    return {
		imgarray: [],  // 存储图片数据，格式: [{ id: 1, url: 'blob:...' }]
		nextId: 1,     // 用于生成唯一ID
	//   viewerVisible: false, // 控制查看器的显示状态
	//         viewerIndex: 0, // 当前查看的图片索引
    };
  },
  mounted() {
  	this.examInfo = JSON.parse(sessionStorage.getItem('examInfo'))
	// if(sessionStorage.getItem('imgarray')){
	// 	this.imgarray = JSON.parse(sessionStorage.getItem('imgarray'));
	// 	// this.$emit('image-uploaded', this.imgarray);
	// }
	this.modeltab()
	// 初始化viewer实例
    // this.$viewer = this.$refs.viewer.$viewer;
  },
    components: {
      draggable 
    },
  methods: {
	modeltab(){
		let obj={
			itemCaseflagid:this.$route.query.modelid
		}
		getitemcaseflagImage(obj).then(res=>{
			this.imgarray = [];
				if(res.obj.cardfront) {
					this.imgarray.push({page:1, url:res.obj.cardfront,itecaseflageid:res.obj.itemCaseflagid});
				}
				if(res.obj.cardreverse) {
					this.imgarray.push({page:2, url:res.obj.cardreverse,itecaseflageid:res.obj.itemCaseflagid});
			}
			sessionStorage.setItem('imgarray',JSON.stringify(this.imgarray))
			this.$emit('imageurllist',this.imgarray)
		})
	},
	 // 处理文件上传
	//  handleFileChange(e) {
    //   const files = e.target.files;
    //   if (!files.length) return;

    //   Array.from(files).forEach(file => {
	// 	console.info(file)
    //     if (!file.type.startsWith('image/')) {
    //       alert('请上传图片文件！');
    //       return;
    //     }

    //     const reader = new FileReader();
    //     reader.onload = (event) => {
	// 		this.imgarray.push({
	// 			page: this.nextId++,
	// 			url: event.target.result,  // Base64（临时使用）
	// 			name: file.name,           // 文件名
	// 			size: file.size,           // 文件大小
	// 			type: file.type         // 文件类型
	// 		});
	// 		// 存储到 sessionStorage（仅关键信息）
	// 		sessionStorage.setItem('imageList', JSON.stringify(this.imgarray.map(img => ({
	// 			page: img.page,
	// 			name: img.name,
	// 			size: img.size,
	// 			type: img.type,
	// 			url:img.url
	// 		}))));
	// 	}
    //     reader.readAsDataURL(file);  // 转换为Base64
    //   });
    //   e.target.value = '';  // 清空input，允许重复上传相同文件
    // },

    // 删除图片
    deleteImage(index,url,itemCaseFlagId,page) {
		if(itemCaseFlagId){
			let obj={filepath:url,pagetype:page,itemcaseflagid:itemCaseFlagId}
			deletecardImage(obj).then(res => {
				if(res.code==0){
					this.imgarray.splice(index, 1);
					this.$message.success('删除成功');
					sessionStorage.setItem('imgarray', JSON.stringify(this.imgarray));
				}else{
					this.$message.error(res.msg || '删除失败');
				}
			})
		}else{
			this.imgarray.splice(index, 1);
		}
		
    //   sessionStorage.setItem('imageList', JSON.stringify(this.imgarray.map(img => ({
    },
	  // 获取模板
	//   modeltab(){
	//   	const url =  `/template/examcourse/${this.examInfo.id}`;
	//   	get(url)
	//   	.then(res => {
	//   		if(res.code==200){
	//   			this.imgarray = [...res.data.templateImages,...this.imgarray]
	// 			this.$emit('imageurllist',this.imgarray)
	// 			this.onlinetemplate = res.data.templateImages
	//   		}
	//   	})
	//   	.catch(error => {
	//   		 this.$message.error(error.message); 
	//   	});
	//   },
	  onEnd(event) {
		const newIndex = event.newIndex;
			// 更新拖拽元素的 page 值
			this.imgarray.forEach((image, index) => {
		    image.page = index + 1; // 更新 page 属性为新的索引值加 1
	   })
	   this.$emit('image-uploaded', this.imgarray);
		// //console.info(this.imgarray)
	  },
		onMoveCallback(list){
			// //console.info(this.imgarray)
			// //console.info(list)
		},
		handleFileChange(event) {
			console.info(event.target)
			const files = event.target.files;
			
			if (!files || files.length === 0) return;
			// sessionStorage.setItem('imgFiles', JSON.stringify(files));
			Array.from(files).forEach((file, index) => {
				// 创建FormData对象
				// const formData = new FormData();
				// formData.append('imgUrl', file);
				// for (let [key, value] of formData.entries()) {
				// 	console.log(key, value);
				// }
				// 显示上传进度
				const loading = this.$loading({
					lock: true,
					text: `正在上传第 ${index + 1} 个文件...`,
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				// 调用上传API
				let obj={imgFile:file}
				uploadcardImage(obj).then(res => {
					loading.close();
					if(res.error === 0) {
						this.imgarray.push({
							page: this.imgarray.length + 1,
							url: res.url, // 假设返回的是图片URL
						});
						this.$emit('image-uploaded', this.imgarray);
						sessionStorage.setItem('imgarray', JSON.stringify(this.imgarray));
					} else {
						this.$message.error(res.message || '上传失败');
					}
				}).catch(error => {
					loading.close();
					this.$message.error(error.message || '上传出错');
				});
			});
			
			// 清空input，允许重复上传相同文件
			event.target.value = '';
		},
    }
};
</script>

<style scoped>
	.uploadlist{
		display: flex;
		align-items: center;
	}
.upload-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  position:relative;
  width:200px;
  height:140px;
  margin:22px 0;
}
.image-preview img {
  width:200px;
 height:140px;
}
.uploadBoxinfo{
	box-sizing: border-box;
	width: 200px;
	height: 140px;
	background: #FFFFFF;
	border-radius: 10px;
	border: 1px dashed #D8E4F0;
	text-align: center;
	padding-top:28px;
	font-size:16px;
	color:#295CFF;
	cursor: pointer;
	position:absolute;
	z-index:1;
}
.uploadBoxinfo i{
	display:block;
	color:#D8E4F0;
	padding:5px 0;
}
.fileIndex{
	position:absolute;
	left:0;
	top:0;
	width:100%;
	height:100%;
	z-index:2;
	cursor: pointer;
	opacity: 0;
}
.imgmove span{
	display: flex;
	align-items: center;
	margin:0 13px;
}
.imgmove span div{
	margin:0 13px;
}
.boxsetdelecte{
	position:relative;
}
.boxsetdelecte span{
	position:absolute;
	left:-24px;
	top:24px;
}
.buttonboxedit{
	display: flex;
	align-items: center;
	justify-content: center;
	padding-top:5px;
}
.buttonboxedit i{
	width: 52px;
	height: 24px;
	background: #295cff1a;
	border-radius: 12px;
	font-size: 16px;
	color: #295CFF;
	text-align: justify;
	line-height:24px;
	text-align: center;
	font-style:normal;
	cursor: pointer;
}
.buttonboxedit i:last-child{
	background: #ec555a1a;
	color:#EC555A;
	margin-left:15px;
}
.boxsetdelecte b{
	display: block;
	text-align: center;
	font-size:20px;
	padding-bottom:6px;
}
</style>